<?php
session_start();
// 数据库连接配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: ". $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["login"])) {
    $username = $_POST["username"];
    $passwordInput = $_POST["password"];
    $captcha = $_POST["captcha"];

    // 验证验证码
    if ($captcha!== $_SESSION["captcha"]) {
        echo "验证码错误";
        exit;
    }

    // 检查普通用户
    $sql = "SELECT * FROM users WHERE username = '$username'";
    $result = $conn->query($sql);

    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
        // 使用 password_verify 验证密码
        if (password_verify($passwordInput, $row['password'])) {
            echo "登录成功";
            $_SESSION["username"] = $username;
            $_SESSION["user_id"] = $row['id'];
        } else {
            echo "用户名或密码错误";
        }
    } else {
        // 检查管理员
        $adminSql = "SELECT * FROM admins WHERE username = '$username'";
        $adminResult = $conn->query($adminSql);
        if ($adminResult->num_rows == 1) {
            $row = $adminResult->fetch_assoc();
            // 使用 password_verify 验证密码
            if (password_verify($passwordInput, $row['password'])) {
                echo "登录成功";
                $_SESSION["username"] = $username;
                $_SESSION["user_id"] = $row['id'];
                $_SESSION["admin"] = true;
            } else {
                echo "用户名或密码错误";
            }
        } else {
            echo "用户名或密码错误";
        }
    }
}

$conn->close();
?>
